package com.nacos.prac.controller;

import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * NacosController
 *
 * @author H
 * @version 1.0
 * @date 2023-11-23 17:46
 */
@RestController
@RequestMapping("nacos")
@Slf4j
public class NacosController {
    @Value("${server.port}")
    private String serverPort;
    /**
     * 注册表信息接口
     */
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/echo/{string}")
    public String echo(@PathVariable String string) {
        return "Hello Nacos Discovery " + string + "==" + serverPort;
    }

    @GetMapping(value = "/discovery")
    public List<String> discovery() {
        List<String> services = discoveryClient.getServices();
        for (String serviceName : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
            for (ServiceInstance instance : instances) {
                HashMap<String, Object> map = new HashMap<>(16);
                map.put("uri", instance.getUri());
                map.put("serviceId", instance.getServiceId());
                map.put("serviceName", serviceName);
                map.put("serviceHost", instance.getHost());
                map.put("servicePort", instance.getPort());
                map.put("serviceMetaData", instance.getMetadata());
                log.info("serviceName: {}, instance: {}", serviceName, instance);
                log.info(map.toString());
            }
        }
        return services;
    }

}
